package demo

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

// MyPost 退单
func MyPost(s string) {
	url := "xxxxxxxxx"

	applyId := s
	refundDate := "2022-09-21"
	reason := "业务关闭直接退单停售"
	operatorId := "3434"
	operatorName := "董长磊"
	defaultingSource := "2"
	reasonType := "99"

	post := "{\"applyId\":\"" + applyId +
		"\",\"defaultingSource\":\"" + defaultingSource +
		"\",\"refundDate\":\"" + refundDate +
		"\",\"reasonType\":\"" + reasonType +
		"\",\"reason\":\"" + reason +
		"\",\"operatorId\":\"" + operatorId +
		"\",\"operatorName\":\"" + operatorName +
		"\"}"

	fmt.Println(url, "post", post)

	var jsonStr = []byte(post)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "xxxx")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("status", resp.Status)
	fmt.Println("response:", resp.Header)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("response Body:", string(body))

}

type jrfyResult struct {
	YxfyAmount           float64 `json:"yxfyAmount"`
	FinanceServiceAmount float64 `json:"financeServiceAmount"`
	GpsCost              float64 `json:"gpsCost"`
	GapAmount            float64 `json:"gapAmount"`
	GpsRebate            float64 `json:"gpsRebate"`
}

type jsonResp[T jrfyResult] struct {
	Ok        bool   `json:"ok"`
	ErrorCode string `json:"errorCode"`
	ErrorMsg  string `json:"errorMsg"`
	Data      T      `json:"data"`
}

// TcJrCost 回扣
func TcJrCost(s string) *jrfyResult {

	url_ := "xxxxxx"

	params := url.Values{}

	Url, err := url.Parse(url_)
	if err != nil {
		return &jrfyResult{}
	}
	params.Set("orderNo", s)
	params.Set("businessType", "4")
	Url.RawQuery = params.Encode()
	path := Url.String()
	fmt.Println(path)

	client := &http.Client{}
	req, err := http.NewRequest(http.MethodGet, path, nil)
	if err != nil {
		panic("处理请求异常")
	}
	req.Header.Add("Authorization", "xxxxxxx")
	req.Header.Add("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		panic("连接异常")
	}
	defer resp.Body.Close()
	var result jsonResp[jrfyResult]
	json.NewDecoder(resp.Body).Decode(&result)
	fmt.Println(result)
	return &result.Data
}
